import React from "react";
import {Redirect} from 'react-router';
import {renderRoutes} from "react-router-config";
import {errorMsg, isLogin, queryState} from "@/util/global";
import store from "../store";
import {INIT_USER_INFO} from "@/store/common/user/type";
import {fromBase64, toBase64} from "@/util/CodeUtils";
import {regainUserInfo} from "@/api/SysUserInfo";
import {connect} from "react-redux";
import {headerTopVisible} from "@/common/header/store/action";

const _ = require("lodash");

class RouterFilter extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {

    }

    shouldComponentUpdate(nextProps, nextState, nextContext) {
        let temp = this.props.RT !== window.location.pathname;
        if (temp && isLogin()) {
            /* 实时更新 */
            // regainUserInfo()
            //     .then(response => {
            //         if (response.data) {
            //             let action = {
            //                 type: INIT_USER_INFO,
            //                 value: response.data
            //             };
            //             store.dispatch(action);
            //             sessionStorage.setItem('just-game-obj', toBase64(response.data));
            //         }
            //     })
        }
        return temp;
    }

    render() {
        const {routerConfig, location} = this.props;
        const {pathname} = location;
        /* 每次页面刷新或者路由跳转时获取存储在内存上的用户信息 */
        let userInfo = sessionStorage.getItem('just-game-obj');
        if (!_.isNull(userInfo)) {
            let action = {
                type: INIT_USER_INFO,
                value: JSON.parse(fromBase64(userInfo))
            };
            store.dispatch(action);
        }

        // 用于递归的回调函数
        function toFindRouter(routes) {
            for (let item in routes) {
                let currentRouter = routes[item];
                if (currentRouter.path === pathname) {
                    Config = currentRouter;
                    return true;
                } else if (!_.isNull(currentRouter.routes)) {
                    if (toFindRouter(currentRouter.routes)) {
                        break;
                    }
                }
            }
            return false;
        }

        // 获取想要前往的Router相关Config
        let Config = '';

        // 起始循环
        for (let item in routerConfig) {
            let currentRouter = routerConfig[item];
            if (currentRouter.path === pathname) {
                Config = currentRouter
                break;
            } else if (currentRouter.routes && currentRouter.routes.length > 0 && !_.isNull(currentRouter.routes)) {
                if (toFindRouter(currentRouter.routes))
                    break;
            }
        }

        // 找不到合适的Router适配
        if (_.isEmpty(Config)) {
            // store.dispatch(setWindowRouter("/404"));
            return <Redirect to="/404"/>;
        }
        this.props.handleHeaderVisible(!Config.fullScreen)
        // 路径名
        const targetRouterConfig = Config.path
        // 是否已经登录
        const isLogin = !_.isNull(queryState('user.id'));
        // 没登录且路由不需要登录权限
        if (!Config.auth && !isLogin) {
            // store.dispatch(setWindowRouter(targetRouterConfig));
            return (renderRoutes(routerConfig))
        }
        if (isLogin) {
            // 防止重复登录
            if (pathname.indexOf("/login") !== -1) {
                // 已经登陆且还要访问登陆界面，重定向到首页
                // errorMsg("您已登录请勿重复操作")
                // return <Redirect to="/"/>;
                // store.dispatch(setWindowRouter(targetRouterConfig));
                return (renderRoutes(routerConfig));
            } else {
                // 已经登录，且访问的路径存在
                if (targetRouterConfig) {
                    if (targetRouterConfig.admin === true && parseInt(queryState('user.isAdmin')) !== 1) {
                        errorMsg("您不是管理员，因此您无权访问该页面！")
                        // store.dispatch(setWindowRouter("/403"));
                        return <Redirect to="/403"/>;
                    }
                    // store.dispatch(setWindowRouter(targetRouterConfig));
                    return (renderRoutes(routerConfig));

                } else {
                    // 已经登录，但访问的路径不存在
                    // store.dispatch(setWindowRouter("/404"));
                    return <Redirect to="/404"/>;
                }
            }
        } else {
            // 未登录，且需要登录
            // store.dispatch(setWindowRouter("/login"));
            return <Redirect to="/login"/>;
        }
    }
}

const mapStateToProps = (state) => {
    return {
        RT: state.getIn(['window', 'router']),
    }
}
const mapStateToDispatch = (dispatch) => {
    return {
        handleHeaderVisible(bool){
            dispatch(headerTopVisible(!!bool))
        }
    }
}
export default connect(mapStateToProps, mapStateToDispatch)(RouterFilter);
